﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;

namespace NextDart
{
    public partial class Settings : Form
    {
        Configuration m_config;
        NextDartConfiguration m_section;

        public Settings()
        {
            InitializeComponent();
        }

        private void Settings_Load(object sender, EventArgs e)
        {
            m_config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            m_section = m_config.GetSection("nextDartConfiguration") as NextDartConfiguration;

            txtDiscard.Text = m_section.DiscardInterval.ToString();

            cmbNorthOrSouth.Text = m_section.NorthBound ? "North" : "South";

            txtLink.Text = m_section.Link;
            toolTip1.SetToolTip(txtLink, m_section.Link);
            ParseLink();
        }

        private void ParseLink()
        {
            int pos = txtLink.Text.IndexOf('?');
            if (pos == -1) return;
            ++pos;

            string right = txtLink.Text.Substring(pos);
            string[] parts = right.Split('&');

            foreach (string part in parts)
            {
                string[] bits = part.Split('=');
                bits[0] = bits[0].ToLower();
                switch (bits[0])
                {
                    case "station":
                        txtStationName.Text = bits[1];
                        break;
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            m_section.Link = txtLink.Text;
            m_section.DiscardInterval = Convert.ToInt32(txtDiscard.Text);
            m_section.NorthBound = (cmbNorthOrSouth.Text == "North");

            NextDartConfiguration.Instance = m_section;
            m_config.Save();
            Close();
            DialogResult = DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
            DialogResult = DialogResult.Cancel;
        }

        private void txtLink_TextChanged(object sender, EventArgs e)
        {
            ParseLink();
        }
    }
}
